package com.example.club.test

import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.example.club.R
import com.example.lib_common.Router
import com.example.lib_common.flow_eventbus.event.LoginEvent
import com.example.lib_common.flow_eventbus.observe.observeEvent
import com.example.lib_common.flow_eventbus.post.postEvent
import com.example.lib_common.flow_eventbus.utils.removeStickyEvent
import com.example.lib_common.livedata_eventbus.LiveEventBus2
import dagger.hilt.android.AndroidEntryPoint

/**
(1)mVersion(livedata的，只要调用setValue，值+1)
(2)mLastVersion（是observer，当onChanged接受数据，值等于mVersion）
(3)数据如何更新？
a。setValue():mVersion++->considerNotify
b。considerNotify():判断mVersion和mLastversion的值
mLastVersion >= mVersion :retrun 不执行
mLastVersion < mVersion: mLastVersion = mVersion，触发onchange方法
 */
@AndroidEntryPoint
class TestActivity : AppCompatActivity() {

    private val mViewModel: TestViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_test)


        mViewModel.testLiveData.observe(this) {//接收
            println("收到数据 $it")
        }
        /*
          解决过数据倒灌的livedata
           */
        LiveEventBus2.postSticky("123", "666666")
    }

    fun toMain(view: View) {
        ARouter.getInstance().build(Router.Ui.MainActivity).navigation()
    }

    fun postLoginEvent(view: View) {//他这个流没有出现数据倒灌的情况
        postEvent(LoginEvent())
    }

    fun observe(view: View) {
        observeEvent<LoginEvent> {
            println("收到登录事件")
        }
    }

    fun observeSticky(view: View) {
        observeEvent<LoginEvent>(isSticky = true) {
            println("收到登录事件")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        removeStickyEvent(LoginEvent::class.java)
        clearStickyEvent("123")
        //clearAllStickyEvents()

    }
    // 清除特定key的粘性事件
    fun clearStickyEvent(key: String) {
        LiveEventBus2.stickyEvents.remove(key)
    }

    // 清除所有粘性事件
    fun clearAllStickyEvents() {
        LiveEventBus2.stickyEvents.clear()
    }

    fun getData(view: View) {//livedata这个数据倒灌溉还没有解决
        mViewModel.getData()//发送
    }

    /*
    已解决数据倒灌
     */
    fun livedata(view: View) {
        LiveEventBus2.getStickyLiveData("123", String::class.java)
            .observe(this) {
                println("收到数据 $it")
            }
    }



}